package ReadXML;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;

public class ImageLoader{

    private String url;
    private RecordStore rs;
    private final String RECORD_NAME="ImageList";

    public ImageLoader() {
        deleteRecordStore();
        try {
            rs = RecordStore.openRecordStore(RECORD_NAME, true);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
    }

    public void loadNSave() {
        HttpConnection hc = null;
        InputStream in = null;
        try {
            hc = (HttpConnection) Connector.open(url);
            int length = (int) hc.getLength();
            byte[] data = null;
            if (length != -1) {
                data = new byte[length];
                in = hc.openInputStream();//new DataInputStream(hc.openInputStream());
                in.read(data);
            } else {
                in = hc.openInputStream();//new DataInputStream(hc.openInputStream());
                ByteArrayOutputStream byteA = new ByteArrayOutputStream();
                int ch;
                while ((ch = in.read()) != -1) {
                    byteA.write(ch);
                }
                data = byteA.toByteArray();
            }

            try {
                rs.addRecord(data, 0, data.length);
            } catch (RecordStoreNotOpenException ex) {
                ex.printStackTrace();
                System.out.println("Exception "+ex.toString());
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
                System.out.println("Exception "+ex.toString());
            }

        } catch (IOException ioe) {
            System.out.println("Exception "+ioe.toString());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (hc != null) {
                    hc.close();
                }
            } catch (IOException ioe) {
                System.out.println("Exception "+ioe.toString());
            }
        }
    }

    private void deleteRecordStore() {
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore(RECORD_NAME);
            } catch (RecordStoreNotOpenException ex) {
                ex.printStackTrace();
                System.out.println("Exception "+ex.toString());
            }catch (RecordStoreException ex) {
                ex.printStackTrace();
                System.out.println(ex.toString());
            }
        }
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
